'''
Author: xialang333@gmail.com
Date: 2024-07-11 15:19:52
LastEditTime: 2024-08-02 14:35:30
'''
# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：xialang333@gmail.com
# Time       ：2024/4/13 10:08
# Description：
"""
import os
import json
import platform
import subprocess
import time
import sys
from io import StringIO
from rest_framework import serializers
from apps.crond.models import TaskMethod
from application.settings import BASE_DIR
from utils.jsonResponse import DetailResponse, ErrorResponse
from utils.serializers import CustomModelSerializer
from utils.viewset import CustomModelViewSet


class  TaskMethodSerializer(CustomModelSerializer):
    """脚本管理 序列化器"""


    class Meta:
        model = TaskMethod
        fields = "__all__"


class TaskMethodViewSet(CustomModelViewSet):
    """
    脚本管理
    """
    queryset = TaskMethod.objects.all()
    serializer_class = TaskMethodSerializer
    search_fields = ('id','name','language_type')

    # 预执行
    def pre_check(self, request, *args, **kwargs):
        script_type = request.data['language_type']
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        if script_type == "shell":
            script_path = os.path.join(BASE_DIR, "media")
            if platform.system() == "Windows":
                return ErrorResponse(msg="不支持该类型脚本执行", data=None)
            else:
                file = str(script_path)+"/"+'temp_script.sh'

            
            with open(file, 'w') as f:
                f.write(request.data['content'])
            result = subprocess.run(['bash', file], capture_output=True, text=True).stdout
            res = {"date_time": current_time, "output": result}
            obj = TaskMethod.objects.filter(id=request.data["id"]).first()
            if obj.pre_exec_log:
                _tmp = obj.pre_exec_log
                _tmp.append(json.dumps(res))
            else:
                obj.pre_exec_log = [json.dumps(res)]
            obj.save()
        elif script_type == "python":
            original_stdout = sys.stdout
            captured_output = StringIO()
            sys.stdout = captured_output
            exec(request.data['content'])
            sys.stdout = original_stdout
            res = {"date_time": current_time, "output": captured_output.getvalue()}
            obj = TaskMethod.objects.filter(id=request.data["id"]).first()
            if obj.pre_exec_log:
                _tmp = obj.pre_exec_log
                _tmp.append(json.dumps(res))
            else:
                obj.pre_exec_log = [json.dumps(res)]
            obj.save()
        return DetailResponse(data=None, msg="执行成功")